package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConst;
import com.atguigu.gulimall.ware.dao.PurchaseDetailDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.DoneVO;
import com.atguigu.gulimall.ware.vo.PurchaseItemVO;
import com.atguigu.gulimall.ware.vo.PurchaseMergeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Autowired
    private PurchaseDetailDao purchaseDetailDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils unreceivedList(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<PurchaseEntity>()
                .eq("status", WareConst.PurchaseEnum.CREATED.getCode()).or().eq("status", WareConst.PurchaseEnum.DISTRIBUTED.getCode());
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), wrapper);

        return new PageUtils(page);

    }

    @Override
    @Transactional
    public void mergeDetails(PurchaseMergeVO purchaseMergeVO) {
        List<Long> detailIds = purchaseMergeVO.getItems();
        Long purchaseId = purchaseMergeVO.getPurchaseId();
        if (purchaseId == null) {
            //新增采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConst.PurchaseEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);

            purchaseId = purchaseEntity.getId();
        }
        //todo 确认采购单状态是0或1才可以合并

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = detailIds.stream().map(detailId -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(detailId);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConst.PurchaseDetailEnum.DISTRIBUTED.getCode());
            return purchaseDetailEntity;

        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }

    @Override
    @Transactional
    public void receive(List<Long> purchaseIds) {
        //1,确认当前采购单是新建或已分配状态
        List<PurchaseEntity> collect1 = purchaseIds.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            if (item.getStatus() == WareConst.PurchaseEnum.CREATED.getCode() ||
                    item.getStatus() == WareConst.PurchaseEnum.DISTRIBUTED.getCode()) {
                return true;
            }
            return false;
        }).map(item->{
            item.setStatus(WareConst.PurchaseEnum.RECEIVED.getCode());
            item.setUpdateTime(new Date());

            List<PurchaseDetailEntity> detailEntities = purchaseDetailDao.selectList(new QueryWrapper<PurchaseDetailEntity>()
                    .eq("purchase_id", item.getId()));
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(detailEntity -> {
                //要不要new一个再设置id？
                detailEntity.setStatus(WareConst.PurchaseDetailEnum.PURCHASING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);

            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(collect1);

        //2,改变采购单状态
//        List<PurchaseEntity> entityList = collect1.stream().map(id -> {
//            PurchaseEntity purchaseEntity = new PurchaseEntity();
//            purchaseEntity.setId(id.getId());
//            purchaseEntity.setUpdateTime(new Date());
//            List<PurchaseDetailEntity> detailEntities = purchaseDetailDao.selectList(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", id));
//
//            List<PurchaseDetailEntity> collect = detailEntities.stream().map(detailEntity -> {
//                detailEntity.setStatus(WareConst.PurchaseDetailEnum.PURCHASING.getCode());
//                return detailEntity;
//            }).collect(Collectors.toList());
//            purchaseDetailService.updateBatchById(collect);
//
//            purchaseEntity.setStatus(WareConst.PurchaseEnum.RECEIVED.getCode());
//            return purchaseEntity;
//        }).collect(Collectors.toList());
//        this.updateBatchById(entityList);
    }

    @Override
    @Transactional
    public void done(DoneVO doneVo) {
        Long purchaseId = doneVo.getId();
        List<PurchaseItemVO> items = doneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        //1.更新purchase_item状态
        Boolean flag = true;
        for(PurchaseItemVO item:items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus()==WareConst.PurchaseDetailEnum.FAILED.getCode()){
                detailEntity.setStatus(WareConst.PurchaseDetailEnum.FAILED.getCode());
                flag=false;
            }
            else{
                detailEntity.setStatus(WareConst.PurchaseDetailEnum.FINISHED.getCode());
                //3.将成功采购的 入库设置sku库存
                //查出skuId
                PurchaseDetailEntity detail = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(updates);
        //2.更新purchase状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag?WareConst.PurchaseEnum.FINISHED.getCode():
                WareConst.PurchaseEnum.EXCEPTION.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);



    }

}